package org.jawa.learning.dao.ibatis;

import java.util.ArrayList;
import java.util.List;

import org.jawa.core.exception.NotFoundException;
import org.jawa.learning.dao.MenuDao;
import org.jawa.learning.model.Menu;
import org.springframework.stereotype.Repository;

@Repository("menuDao")
public class MenuDaoiBatis extends GenericDaoiBatis<Menu, Long> implements MenuDao {

	public MenuDaoiBatis() {
		super(Menu.class);
	}

	/**
	 * 根据菜单ID 返回菜单.
	 *
	 * @param menuId 菜单ID.
	 * @return 菜单.
	 * @throws NotFoundException 菜单没有找到.
	 */
	public Menu getMenu(Long menuId) throws NotFoundException {
		if (menuId == null) {
			throw new NotFoundException("菜单ID 不可以为空");
		}
		Menu menu = getSqlSession().selectOne("getMenu", menuId);
		return menu;
	}

	/**
	 * 返回上级菜单下的所有直接子菜单
	 * @param parentId
	 * @return
	 */
	public List<Menu> getTopMenus() {
		List<Menu> childrenMenus = new ArrayList<Menu>(100);
		List<Menu> menus = getSqlSession().selectList("getTopMenus");

		Menu menua;
		for (Menu menu : menus) {
			try {
				menua = getMenu(menu.getId());
				childrenMenus.add(menua);
			} catch (Exception e) {
				log.error("获取菜单{}时出错", menu.getId());
			}
		}
		return childrenMenus;
	}

	/**
	 * 返回上级菜单下的所有直接子菜单
	 * @param parentId
	 * @return
	 */
	public List<Menu> getChildrenMenus(Long parentId) {
		return null;
	}

	@Override
	public List<Menu> getMenusByRole(Long roleId) {
		List menus = getSqlSession().selectList("getMenusByRole", roleId);
		return menus;

	}

}
